const moment = require('moment');
const db = require('../config/db');
const fs = require('fs');
const path = require('path');

/**
 * 管理员控制器 - 处理管理员特有功能
 * 包含用户管理、系统配置等管理员权限操作
 */

/**
 * 获取普通用户列表（仅管理员，支持分页）
 * @param {Object} req - 请求对象
 * @param {Object} res - 响应对象
 */
exports.getNormalUsers = async (req, res) => {
  try {
    const { keyword, startDate, endDate, status, page = 1, pageSize = 10 } = req.query;
    const currentPage = parseInt(page, 10);
    const itemsPerPage = parseInt(pageSize, 10);
    const offset = (currentPage - 1) * itemsPerPage;

    const queryParams = [];
    const countParams = [];
    let query = 'SELECT * FROM users WHERE role = 0'; // 0表示普通用户
    let countQuery = 'SELECT COUNT(*) as total FROM users WHERE role = 0';

    // 构建查询条件
    if (keyword) {
      query += ' AND (username LIKE ? OR email LIKE ? OR phone LIKE ?)';
      countQuery += ' AND (username LIKE ? OR email LIKE ? OR phone LIKE ?)';
      const likeKeyword = `%${keyword}%`;
      queryParams.push(likeKeyword, likeKeyword, likeKeyword);
      countParams.push(likeKeyword, likeKeyword, likeKeyword);
    }

    if (startDate) {
      query += ' AND created_at >= ?';
      countQuery += ' AND created_at >= ?';
      queryParams.push(startDate);
      countParams.push(startDate);
    }

    if (endDate) {
      query += ' AND created_at <= ?';
      countQuery += ' AND created_at <= ?';
      queryParams.push(endDate);
      countParams.push(endDate);
    }

    if (status) {
      query += ' AND status = ?';
      countQuery += ' AND status = ?';
      queryParams.push(status);
      countParams.push(status);
    }

    // 添加排序逻辑
    if (req.query.sortBy) {
      const sortBy = req.query.sortBy;
      if (sortBy === 'created_at_asc') {
        query += ' ORDER BY created_at ASC';
      } else if (sortBy === 'created_at_desc') {
        query += ' ORDER BY created_at DESC';
      }
    }

    // 添加分页参数
    query += ' LIMIT ? OFFSET ?';
    queryParams.push(itemsPerPage, offset);

    // 输出调试信息
    console.log(`[${moment().format('YYYY-MM-DD HH:mm:ss')}] [DEBUG] [管理员获取用户列表] SQL: ${query}`);
    console.log(`[${moment().format('YYYY-MM-DD HH:mm:ss')}] [DEBUG] [管理员获取用户列表] 参数: ${JSON.stringify(queryParams)}`);
    console.log(`[${moment().format('YYYY-MM-DD HH:mm:ss')}] [DEBUG] [管理员获取用户列表] 计数SQL: ${countQuery}`);
    console.log(`[${moment().format('YYYY-MM-DD HH:mm:ss')}] [DEBUG] [管理员获取用户列表] 计数参数: ${JSON.stringify(countParams)}`);

    // 执行查询
    const [users] = await db.query(query, queryParams);
    const [countResult] = await db.query(countQuery, countParams);

    const totalItems = countResult[0].total;
    const totalPages = Math.ceil(totalItems / itemsPerPage);

    // 记录查询日志
    console.log(`[${moment().format('YYYY-MM-DD HH:mm:ss')}] [INFO] [管理员用户查询] 请求参数: ${JSON.stringify(req.query)}, 总数量: ${totalItems}, 当前页: ${currentPage}`);

    res.json({
      success: true,
      users,
      pagination: {
        currentPage,
        pageSize: itemsPerPage,
        totalItems,
        totalPages
      }
    });
  } catch (error) {
    console.error(`[${moment().format('YYYY-MM-DD HH:mm:ss')}] [ERROR] [管理员用户查询失败] ${error.message}`);
    res.status(500).json({ success: false, error: '获取用户列表失败' });
  }
};

/**
 * 删除用户（仅管理员）
 * @param {Object} req - 请求对象
 * @param {Object} res - 响应对象
 */
exports.deleteUser = async (req, res) => {
  try {
    const { id } = req.params;

    // 防止删除管理员
    const [user] = await db.execute('SELECT role, avatar_url FROM users WHERE user_id = ?', [id]);
    if (user.length === 0) {
      return res.status(404).json({ success: false, error: '用户不存在' });
    }

    // 执行删除
    await db.execute('DELETE FROM users WHERE user_id = ?', [id]);

    // 删除用户头像图片（排除默认头像）
    const avatarUrl = user[0].avatar_url;
    const defaultAvatar = '/uploads/avatars/default.svg';
    if (avatarUrl && avatarUrl !== defaultAvatar) {
      const avatarPath = path.join(__dirname, '../../uploads/avatars', path.basename(avatarUrl));
      if (fs.existsSync(avatarPath)) {
        fs.unlinkSync(avatarPath);
        console.log(`[${moment().format('YYYY-MM-DD HH:mm:ss')}] [INFO] [删除用户头像] 头像路径: ${avatarPath}`);
      } else {
        console.log(`[${moment().format('YYYY-MM-DD HH:mm:ss')}] [WARN] [删除用户头像] 头像不存在: ${avatarPath}`);
      }
    }

    // 记录删除日志
    console.log(`[${moment().format('YYYY-MM-DD HH:mm:ss')}] [INFO] [管理员删除用户] 用户ID: ${id}, 操作人: ${req.user.username}`);

    res.json({ success: true, message: '用户已成功删除' });
  } catch (error) {
    console.error(`[${moment().format('YYYY-MM-DD HH:mm:ss')}] [ERROR] [管理员删除用户失败] ${error.message}`);
    res.status(500).json({ success: false, error: '删除用户失败' });
  }
};

/**
 * 更新用户信息（仅管理员）
 * @param {Object} req - 请求对象
 * @param {Object} res - 响应对象
 */
exports.updateUser = async (req, res) => {
  try {
    const { id } = req.params;
    const { email, phone, status } = req.body;

    // 验证必要参数
    if (!email || !status) {
      return res.status(400).json({ success: false, error: '邮箱和状态为必填项' });
    }

    // 检查用户是否存在
    const [user] = await db.execute('SELECT * FROM users WHERE user_id = ?', [id]);
    if (user.length === 0) {
      return res.status(404).json({ success: false, error: '用户不存在' });
    }

    // 防止更新管理员
    if (user[0].role === 1) {
      return res.status(403).json({ success: false, error: '禁止修改管理员信息' });
    }

    // 执行更新
    await db.execute(
      'UPDATE users SET email = ?, phone = ?, status = ?, updated_at = ? WHERE user_id = ?',
      [email, phone || null, status, moment().format('YYYY-MM-DD HH:mm:ss'), id]
    );

    // 记录更新日志
    console.log(`[${moment().format('YYYY-MM-DD HH:mm:ss')}] [INFO] [管理员更新用户] 用户ID: ${id}, 操作人: ${req.user.username}`);

    res.json({ success: true, message: '用户信息已成功更新' });
  } catch (error) {
    console.error(`[${moment().format('YYYY-MM-DD HH:mm:ss')}] [ERROR] [管理员更新用户失败] ${error.message}`);
    res.status(500).json({ success: false, error: '更新用户信息失败' });
  }
};

/**
 * 获取用户详情（仅管理员）
 * @param {Object} req - 请求对象
 * @param {Object} res - 响应对象
 */
exports.getUserById = async (req, res) => {
  try {
    const { id } = req.params;

    // 查询用户信息
    const [users] = await db.execute('SELECT * FROM users WHERE user_id = ?', [id]);
    if (users.length === 0) {
      return res.status(404).json({ success: false, error: '用户不存在' });
    }

    // 记录查询日志
    console.log(`[${moment().format('YYYY-MM-DD HH:mm:ss')}] [INFO] [管理员获取用户详情] 用户ID: ${id}`);

    res.json({ success: true, user: users[0] });
  } catch (error) {
    console.error(`[${moment().format('YYYY-MM-DD HH:mm:ss')}] [ERROR] [管理员获取用户详情失败] ${error.message}`);
    res.status(500).json({ success: false, error: '获取用户详情失败' });
  }
};

/**
 * 获取商品列表（仅管理员，支持分页）
 * @param {Object} req - 请求对象
 * @param {Object} res - 响应对象
 */
exports.getProducts = async (req, res) => {
  try {
    const { keyword, category_id, sortByTime, sortByPrice, status, page = 1, pageSize = 10 } = req.query;
    const currentPage = parseInt(page, 10);
    const itemsPerPage = parseInt(pageSize, 10);
    const offset = (currentPage - 1) * itemsPerPage;

    // 查询商品数据
    let query = 'SELECT product_id, seller_id, category_id, title AS name, description, CAST(price AS DECIMAL(10,2)) AS price, CAST(original_price AS DECIMAL(10,2)) AS original_price, status, view_count, created_at, updated_at FROM products WHERE 1=1';
    // 查询总数量
    let countQuery = 'SELECT COUNT(*) as total FROM products WHERE 1=1';
    const queryParams = [];
    const countParams = [];

    // 关键字搜索
    if (keyword) {
      query += ' AND (title LIKE ? OR description LIKE ?)';
      countQuery += ' AND (title LIKE ? OR description LIKE ?)';
      const searchTerm = `%${keyword}%`;
      queryParams.push(searchTerm, searchTerm);
      countParams.push(searchTerm, searchTerm);
    }

    // 分类筛选
    if (category_id) {
      query += ' AND category_id = ?';
      countQuery += ' AND category_id = ?';
      queryParams.push(category_id);
      countParams.push(category_id);
    }

    // 状态筛选
    if (status !== undefined) {
      const statusNum = parseInt(status, 10);
      query += ' AND status = ?';
      countQuery += ' AND status = ?';
      queryParams.push(statusNum);
      countParams.push(statusNum);
    }

    // 排序逻辑
    const sortConditions = [];
    if (sortByTime === 'created_at_asc') {
      sortConditions.push('created_at ASC');
    } else if (sortByTime === 'created_at_desc') {
      sortConditions.push('created_at DESC');
    }

    if (sortByPrice === 'price_asc') {
      sortConditions.push('price ASC');
    } else if (sortByPrice === 'price_desc') {
      sortConditions.push('price DESC');
    }

    if (sortConditions.length > 0) {
      query += ' ORDER BY ' + sortConditions.join(', ');
    }

    // 添加分页参数
    query += ' LIMIT ? OFFSET ?';
    queryParams.push(itemsPerPage, offset);

    // 输出调试信息
    console.log(`[${moment().format('YYYY-MM-DD HH:mm:ss')}] [DEBUG] [管理员获取商品列表] SQL: ${query}`);
    console.log(`[${moment().format('YYYY-MM-DD HH:mm:ss')}] [DEBUG] [管理员获取商品列表] 参数: ${JSON.stringify(queryParams)}`);
    console.log(`[${moment().format('YYYY-MM-DD HH:mm:ss')}] [DEBUG] [管理员获取商品列表] 计数SQL: ${countQuery}`);
    console.log(`[${moment().format('YYYY-MM-DD HH:mm:ss')}] [DEBUG] [管理员获取商品列表] 计数参数: ${JSON.stringify(countParams)}`);

    // 执行查询（修改参数传递方式）
    const [products] = await db.query(query, queryParams);
    const [countResult] = await db.query(countQuery, countParams);

    const totalItems = countResult[0].total;
    const totalPages = Math.ceil(totalItems / itemsPerPage);

    // 记录查询日志
    console.log(`[${moment().format('YYYY-MM-DD HH:mm:ss')}] [INFO] [管理员获取商品列表] 参数: ${JSON.stringify(req.query)}, 总数量: ${totalItems}, 当前页: ${currentPage}`);

    res.json({
      success: true,
      products,
      pagination: {
        currentPage,
        pageSize: itemsPerPage,
        totalItems,
        totalPages
      }
    });
  } catch (error) {
    console.error(`[${moment().format('YYYY-MM-DD HH:mm:ss')}] [ERROR] [管理员获取商品列表失败] ${error.message}`);
    res.status(500).json({ success: false, error: '获取商品列表失败' });
  }
};

// 获取所有商品分类（扁平结构）
exports.getAllCategories = async (req, res) => {
  try {
    console.log(`[${moment().format('YYYY-MM-DD HH:mm:ss')}] [INFO] 获取所有商品分类请求`);
    const [categories] = await db.query('SELECT category_id, name, icon_url FROM categories');
    res.json({ categories: categories });
  } catch (err) {
    console.error(`[${moment().format('YYYY-MM-DD HH:mm:ss')}] [ERROR] 获取分类失败: ${err.message}`);
    res.status(500).json({ message: '获取分类失败', error: err.message });
  }
};

/**
 * 更新商品状态（仅管理员）
 * @param {Object} req - 请求对象
 * @param {Object} res - 响应对象
 */
exports.updateProductStatus = async (req, res) => {
  try {
    const { id } = req.params;
    const { status } = req.body;

    // 参数验证
    if (status === undefined) {
      return res.status(400).json({ success: false, error: '状态参数不能为空' });
    }

    // 检查商品是否存在
    const [existingProducts] = await db.execute('SELECT * FROM products WHERE product_id = ?', [id]);
    if (existingProducts.length === 0) {
      return res.status(404).json({ success: false, error: '商品不存在' });
    }

    // 更新商品状态
    await db.execute(
      'UPDATE products SET status = ?, updated_at = ? WHERE product_id = ?',
      [status, moment().format('YYYY-MM-DD HH:mm:ss'), id]
    );

    // 记录更新日志
    console.log(`[${moment().format('YYYY-MM-DD HH:mm:ss')}] [INFO] [管理员更新商品状态] 商品ID: ${id}, 新状态: ${status}`);

    res.json({ success: true, message: '商品状态更新成功' });
  } catch (error) {
    console.error(`[${moment().format('YYYY-MM-DD HH:mm:ss')}] [ERROR] [管理员更新商品状态失败] ${error.message}`);
    res.status(500).json({ success: false, error: '更新商品状态失败' });
  }
};


// 已删除无用的disableProduct和enableProduct方法，统一使用updateProductStatus方法


/**
 * 获取所有交易列表（仅管理员，支持分页和筛选）
 * @param {Object} req - 请求对象
 * @param {Object} res - 响应对象
 */
exports.getTransactions = async (req, res) => {
  try {
    const { orderId, productName, buyerName, sellerName, status, startDate, endDate, page = 1, pageSize = 10 } = req.query;
    const currentPage = parseInt(page, 10);
    const itemsPerPage = parseInt(pageSize, 10);
    const offset = (currentPage - 1) * itemsPerPage;

    const queryParams = [];
    const countParams = [];
    let query = `
      SELECT o.order_id, o.product_id, p.title AS product_name, o.buyer_id, u_buyer.username AS buyer_name, 
             o.seller_id, u_seller.username AS seller_name, CAST(p.price AS DECIMAL(10,2)) AS total_amount, 
             o.status, o.created_at, o.updated_at
      FROM orders o
      JOIN products p ON o.product_id = p.product_id
      JOIN users u_buyer ON o.buyer_id = u_buyer.user_id
      JOIN users u_seller ON o.seller_id = u_seller.user_id
      WHERE 1=1
    `;
    let countQuery = `
      SELECT COUNT(*) as total
      FROM orders o
      JOIN products p ON o.product_id = p.product_id
      JOIN users u_buyer ON o.buyer_id = u_buyer.user_id
      JOIN users u_seller ON o.seller_id = u_seller.user_id
      WHERE 1=1
    `;

    // 构建查询条件
    if (orderId) {
      query += ' AND o.order_id LIKE ?';
      countQuery += ' AND o.order_id LIKE ?';
      queryParams.push(`%${orderId}%`);
      countParams.push(`%${orderId}%`);
    }

    if (productName) {
      query += ' AND p.title LIKE ?';
      countQuery += ' AND p.title LIKE ?';
      queryParams.push(`%${productName}%`);
      countParams.push(`%${productName}%`);
    }

    if (buyerName) {
      query += ' AND u_buyer.username LIKE ?';
      countQuery += ' AND u_buyer.username LIKE ?';
      queryParams.push(`%${buyerName}%`);
      countParams.push(`%${buyerName}%`);
    }

    if (sellerName) {
      query += ' AND u_seller.username LIKE ?';
      countQuery += ' AND u_seller.username LIKE ?';
      queryParams.push(`%${sellerName}%`);
      countParams.push(`%${sellerName}%`);
    }

    if (status !== undefined) {
      query += ' AND o.status = ?';
      countQuery += ' AND o.status = ?';
      queryParams.push(parseInt(status, 10));
      countParams.push(parseInt(status, 10));
    }

    if (startDate) {
      query += ' AND o.created_at >= ?';
      countQuery += ' AND o.created_at >= ?';
      queryParams.push(startDate);
      countParams.push(startDate);
    }

    if (endDate) {
      query += ' AND o.created_at <= ?';
      countQuery += ' AND o.created_at <= ?';
      queryParams.push(endDate);
      countParams.push(endDate);
    }

    // 添加排序逻辑
    query += ' ORDER BY o.created_at DESC';

    // 添加分页参数
    query += ' LIMIT ? OFFSET ?';
    queryParams.push(itemsPerPage, offset);

    // 输出调试信息
    console.log(`[${moment().format('YYYY-MM-DD HH:mm:ss')}] [DEBUG] [管理员获取交易列表] SQL: ${query}`);
    console.log(`[${moment().format('YYYY-MM-DD HH:mm:ss')}] [DEBUG] [管理员获取交易列表] 参数: ${JSON.stringify(queryParams)}`);
    console.log(`[${moment().format('YYYY-MM-DD HH:mm:ss')}] [DEBUG] [管理员获取交易列表] 计数SQL: ${countQuery}`);
    console.log(`[${moment().format('YYYY-MM-DD HH:mm:ss')}] [DEBUG] [管理员获取交易列表] 计数参数: ${JSON.stringify(countParams)}`);

    // 执行查询
    const [transactions] = await db.query(query, queryParams);
    const [countResult] = await db.query(countQuery, countParams);

    const totalItems = countResult[0].total;
    const totalPages = Math.ceil(totalItems / itemsPerPage);

    // 记录查询日志
    console.log(`[${moment().format('YYYY-MM-DD HH:mm:ss')}] [INFO] [管理员交易查询] 请求参数: ${JSON.stringify(req.query)}, 总数量: ${totalItems}, 当前页: ${currentPage}`);

    res.json({
      success: true,
      transactions,
      pagination: {
        currentPage,
        pageSize: itemsPerPage,
        totalItems,
        totalPages
      }
    });
  } catch (error) {
    console.error(`[${moment().format('YYYY-MM-DD HH:mm:ss')}] [ERROR] [管理员交易查询失败] ${error.message}`);
    res.status(500).json({ success: false, error: '获取交易列表失败' });
  }
};

/**
 * 获取交易详情（仅管理员）
 * @param {Object} req - 请求对象
 * @param {Object} res - 响应对象
 */
exports.getTransactionDetail = async (req, res) => {
  try {
    const { id } = req.params;

    // 查询交易详情
    const query = `
      SELECT o.order_id, o.product_id, p.title AS product_name, p.description, CAST(p.price AS DECIMAL(10,2)) AS price, 
             CAST(p.price AS DECIMAL(10,2)) AS total_amount, o.buyer_id, u_buyer.username AS buyer_name, 
             u_buyer.email AS buyer_email, u_buyer.phone AS buyer_phone, o.seller_id, u_seller.username AS seller_name, 
             u_seller.email AS seller_email, u_seller.phone AS seller_phone, o.status, o.created_at, o.updated_at
      FROM orders o
      JOIN products p ON o.product_id = p.product_id
      JOIN users u_buyer ON o.buyer_id = u_buyer.user_id
      JOIN users u_seller ON o.seller_id = u_seller.user_id
      WHERE o.order_id = ?
    `;

    // 输出调试信息
    console.log(`[${moment().format('YYYY-MM-DD HH:mm:ss')}] [DEBUG] [管理员获取交易详情] SQL: ${query}`);
    console.log(`[${moment().format('YYYY-MM-DD HH:mm:ss')}] [DEBUG] [管理员获取交易详情] 参数: ${JSON.stringify([id])}`);

    // 执行查询
    const [transactions] = await db.query(query, [id]);

    if (transactions.length === 0) {
      return res.status(404).json({ success: false, error: '交易不存在' });
    }

    // 记录查询日志
    console.log(`[${moment().format('YYYY-MM-DD HH:mm:ss')}] [INFO] [管理员获取交易详情] 订单ID: ${id}`);

    res.json({
      success: true,
      transaction: transactions[0]
    });
  } catch (error) {
    console.error(`[${moment().format('YYYY-MM-DD HH:mm:ss')}] [ERROR] [管理员获取交易详情失败] ${error.message}`);
    res.status(500).json({ success: false, error: '获取交易详情失败' });
  }
};

/**
 * 更新交易状态（仅管理员）
 * @param {Object} req - 请求对象
 * @param {Object} res - 响应对象
 */
exports.updateTransactionStatus = async (req, res) => {
  try {
    const { order_id } = req.params;
    const { status } = req.body;

    // 验证参数
    if (status === undefined) {
      return res.status(400).json({ success: false, error: '状态参数不能为空' });
    }

    // 检查交易是否存在
    const [orders] = await db.execute('SELECT * FROM orders WHERE order_id = ?', [order_id]);

    if (orders.length === 0) {
      return res.status(404).json({ success: false, error: '交易不存在' });
    }

    const order = orders[0];
    const oldStatus = order.status;

    // 更新交易状态
    await db.execute(
      'UPDATE orders SET status = ?, updated_at = ? WHERE order_id = ?',
      [status, moment().format('YYYY-MM-DD HH:mm:ss'), order_id]
    );

    // 记录更新日志
    console.log(`[${moment().format('YYYY-MM-DD HH:mm:ss')}] [INFO] [管理员更新交易状态] 订单ID: ${order_id}, 旧状态: ${oldStatus}, 新状态: ${status}`);

    res.json({ success: true, message: '交易状态更新成功', newStatus: status });
  } catch (error) {
    console.error(`[${moment().format('YYYY-MM-DD HH:mm:ss')}] [ERROR] [管理员更新交易状态失败] ${error.message}`);
    res.status(500).json({ success: false, error: '更新交易状态失败' });
  }
};

/**
 * 取消交易（仅管理员）
 * @param {Object} req - 请求对象
 * @param {Object} res - 响应对象
 */
exports.cancelTransaction = async (req, res) => {
  try {
    const { order_id } = req.params;

    // 检查交易是否存在
    const [orders] = await db.execute('SELECT * FROM orders WHERE order_id = ?', [order_id]);

    if (orders.length === 0) {
      return res.status(404).json({ success: false, error: '交易不存在' });
    }

    const order = orders[0];

    // 检查订单状态是否允许取消
    if (![0, 1, 2, 3].includes(order.status)) {
      return res.status(400).json({ success: false, error: '当前订单状态不允许取消' });
    }

    // 更新订单状态为已取消
    await db.execute(
      'UPDATE orders SET status = 4, updated_at = ? WHERE order_id = ?',
      [moment().format('YYYY-MM-DD HH:mm:ss'), order_id]
    );

    // 记录取消日志
    console.log(`[${moment().format('YYYY-MM-DD HH:mm:ss')}] [INFO] [管理员取消交易] 订单ID: ${order_id}`);

    res.json({ success: true, message: '交易已成功取消' });
  } catch (error) {
    console.error(`[${moment().format('YYYY-MM-DD HH:mm:ss')}] [ERROR] [管理员取消交易失败] ${error.message}`);
    res.status(500).json({ success: false, error: '取消交易失败' });
  }
};

// 创建分类（管理员）
exports.createCategory = async (req, res) => {
  try {
    const { name, icon_url } = req.body;
    console.log(`[${moment().format('YYYY-MM-DD HH:mm:ss')}] [INFO] 创建分类请求: 名称=${name}, 图标URL=${icon_url || '无'}`);

    // 验证分类名称
    if (!name || name.trim() === '') {
      return res.status(400).json({ message: '分类名称不能为空' });
    }

    // 插入新分类
    const [result] = await db.query(
      'INSERT INTO categories (name, icon_url) VALUES (?, ?)',
      [name.trim(), icon_url || null]
    );

    console.log(`[${moment().format('YYYY-MM-DD HH:mm:ss')}] [INFO] 分类创建成功: ID=${result.insertId}`);
    res.status(201).json({
      message: '分类创建成功',
      category: {
        category_id: result.insertId,
        name: name.trim(),
        icon_url: icon_url || null
      }
    });
  } catch (err) {
    console.error(`[${moment().format('YYYY-MM-DD HH:mm:ss')}] [ERROR] 创建分类失败: ${err.message}`);
    res.status(500).json({ message: '创建分类失败', error: err.message });
  }
};
